package com.powernode.config;

import com.powernode.constant.CommonConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 内容:
 * 作者: cy
 */
@Component
public class FeignInterceptor implements RequestInterceptor {


    /**
     * 这个方法 就是拦截的方法  只要是远程调用 都要走这个拦截器  远程调用是直接拿到ip和端口的 属于内部调用 不走网关
     * 1 浏览器--------token------->A-------token------->B
     * 2 A------------->B / MQ---------------->B
     * 3 第三方平台回调我们的接口-------->A----------->B
     *
     * @param template 这个请求 就是远程调用发起的请求
     */
    @Override
    public void apply(RequestTemplate template) {
        // 这个是浏览器访问进来的request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(requestAttributes)) {
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader(CommonConstant.AUTHORIZATION);
            if (StringUtils.hasText(token)) {
                template.header(CommonConstant.AUTHORIZATION, token);
                return;
            }
        }
        template.header(CommonConstant.AUTHORIZATION, "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhbGwiXSwiZXhwIjozNzg5NzEyMjE5LCJqdGkiOiI5YTRkODg4Yy1mM2RiLTRiNDQtYTljZi1hODliNTY1OGEyMTciLCJjbGllbnRfaWQiOiJwb3dlci1zaG9wIn0.mQ6_bP_38maUAo_Gd-WzZwPRm8TNNYVpHdJlH-Zh502cpW4CFI-y6coFQfVCcnWKZoT1yx-NYLdXjfgflaDwQaxjg95gsMYTe7vczw0Oqg0WgZcvbLzRnTZ4FDzgm0ShPzcVjNqsU7u3xRlPOSnSUeAnhG8Lf7aYz609shgj6McCP1M7qZ0fDqerubtUG5TaGxpsXfTkdS2gQP-unIiEY4F1xa0WidHIqg2lAcN0fxrkC_8B1WgTAbBCrwPdk2eyCKK7vx48Elt7_SYH2HZVw2QqDAnCRDh5L0pYt2w6dKMwP8nfQnrAgyfvPbDUKmdYsHxjegSYSgQEmsc0LPOCNw");
    }
}
